﻿using System;
using System.Linq;
using Invoicing.Model;
using Invoicing.Model.Orders;
using Invoicing.Model.Members;
using Invoicing.Model.Products;
using Utils;
namespace Invoicing.Command.Orders
{
    public class DealOrderCommand
    {
        public static DealOrderModel NewOrder(DealOrderModel order)
        {
            if (order != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    var orderMethod = (OrderMethod)Enum.Parse(typeof(OrderMethod), order.Method.ToString());
                    order.OrderNo = Comm.Orders.CreateOrderNo(db, orderMethod);
                    var dOrder = Convertor.ConvertFrom<DealOrder, DealOrderModel>(order);
                    var dItems = Convertor.ConvertFromCollection<DealOrderDetail, DealOrderDetailModel>(order.Items);
                    foreach (var it in dItems)
                        dOrder.DealOrderDetails.Add(it);
                    db.DataContext.DealOrders.Add(dOrder);

                    #region 修改交易单据的状态 判断是否已经完成预订
                    if (order.AssociatedBookID > 0)
                    {
                        var bookOrder = db.DataContext.BookOrders.FirstOrDefault(p => p.ID == order.AssociatedBookID && new int[] { 1, 21 }.Contains(p.OrderStatus));
                        if (bookOrder != null)
                        {

                            var book_items = bookOrder.BookOrderDetails.ToList();
                            var deal_orders = bookOrder.DealOrders.ToList();
                            var hasDone = true;
                            book_items.ForEach(p =>
                            {
                                decimal qua = 0;
                                deal_orders.ForEach(o =>
                                {
                                    qua += o.DealOrderDetails.Where(r => r.ProductID == p.ProductID && r.MaterialID == p.MaterialID && r.ProcessID == p.ProcessID && r.Size == p.Size).Sum(r => r.Quantity);
                                });
                                if (p.Quantity > qua)
                                    hasDone = false;
                            });
                            bookOrder.OrderStatus = (int)(hasDone ? OrderStatus.FinishBook : OrderStatus.Booking);
                        }
                    }
                    #endregion

                    db.DataContext.SaveChanges();
                    order.ID = dOrder.ID;
                    return order;
                }
            }
            return null;
        }
        /// <summary>
        /// 取得最近一次交易的价格
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="SupplierID"></param>
        /// <returns></returns>
        public static decimal GetLastPrice(int productID, int customerID)
        {
            if (productID > 0 && customerID > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.DealOrderDetails.Where(p => p.ProductID == productID && p.DealOrder.CustomerID == customerID).OrderByDescending(p => p.ID).FirstOrDefault();
                    if (d != null)
                        return d.UnitPrice;
                }
            }
            return 0;
        }
        /// <summary>
        /// 查询单据列表
        /// </summary>
        /// <param name="sea"></param>
        /// <returns></returns>
        public static DealOrderCollection GetOrders(DealOrderQuery sea)
        {
            var result = new DealOrderCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<DealOrder> q = db.DataContext.DealOrders;
                if (sea != null)
                {
                    if (!string.IsNullOrEmpty(sea.OrderNo))
                        q = q.Where(p => p.OrderNo == sea.OrderNo);
                    if (sea.CustomerID > 0)
                        q = q.Where(p => p.CustomerID == sea.CustomerID);
                    if (sea.OperatorUserID > 0)
                        q = q.Where(p => p.OperatorUserID == sea.OperatorUserID);
                    if (sea.OrderDateBefore != null)
                        q = q.Where(p => p.NoteDate.CompareTo(sea.OrderDateBefore.Value) >= 0);
                    if (sea.OrderDateAfter != null)
                        q = q.Where(p => p.NoteDate.CompareTo(sea.OrderDateAfter.Value) <= 0);
                    if (sea.Method!=null && sea.Method.Length > 0)
                        q = q.Where(p =>sea.Method.Contains(p.Method));
                    if (sea.OrderStatus!=null && sea.OrderStatus.Length > 0)
                        q = q.Where(p => sea.OrderStatus.Contains(p.OrderStatus));
                }
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderByDescending(p => p.ID);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    result = Convertor.ConvertCollection<DealOrderModel, DealOrder, DealOrderCollection>(lst);
                    result.TotalRecordsCount = n;
                    foreach (var m in result)
                    {
                        var d = lst.Find(p => p.OrderNo == m.OrderNo);
                        if (sea.GetCustomer)
                        {
                            m.Customer = Convertor.ConvertTo<CustomerModel, Customer>(d.Customer);
                            if (sea.GetCustomerCategory)
                                m.Customer.Categories = Convertor.ConvertCollection<CustomerCategoryModel, CustomerCategory, CustomerCategoryCollection>(d.Customer.CustomerCategories);
                        }
                        if (sea.GetOperator)
                        {
                            m.Operator = d.User.RealName;
                        }
                        if (sea.GetItems)
                        {
                            m.Items = Convertor.ConvertCollection<DealOrderDetailModel, DealOrderDetail, DealOrderDetailCollection>(d.DealOrderDetails);
                            foreach (var it in m.Items)
                            {

                                var dit = d.DealOrderDetails.First(p => p.ID == it.ID);
                                if (sea.GetProduct)
                                {
                                    it.Product = Convertor.ConvertTo<ProductModel, Product>(dit.Product);
                                    if (sea.GetProductCategory)
                                        it.Product.Categories = Convertor.ConvertCollection<ProductCategoryModel, ProductCategory, ProductCategoryCollection>(dit.Product.ProductCategories);
                                    if (sea.GetProductMaterial)
                                        it.MaterialName = dit.ProductMaterial.MaterialName;
                                    if (sea.GetProductProcess)
                                        it.ProcessName = dit.ProductProcess.ProcessName;
                                }
                            }
                        }
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 查询单张单据
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public static DealOrderModel GetOrder(string orderNo)
        {
            if (!string.IsNullOrEmpty(orderNo))
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.DealOrders.FirstOrDefault(p => p.OrderNo == orderNo);
                    if (d != null)
                    {
                        var m = Convertor.ConvertTo<DealOrderModel, DealOrder>(d);
                        m.Customer = Convertor.ConvertTo<CustomerModel, Customer>(d.Customer);
                        m.Items = Convertor.ConvertCollection<DealOrderDetailModel, DealOrderDetail, DealOrderDetailCollection>(d.DealOrderDetails);
                        foreach (var o in m.Items)
                        {
                            var di = d.DealOrderDetails.FirstOrDefault(p => p.ID == o.ID);
                            o.Product = Convertor.ConvertTo<ProductModel, Product>(di.Product);
                            o.MaterialName = di.ProductMaterial.MaterialName;
                            o.ProcessName = di.ProductProcess.ProcessName;
                        }
                        return m;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 查询单张单据
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public static DealOrderModel GetOrderWithProductOrders(string orderNo)
        {
            if (!string.IsNullOrEmpty(orderNo))
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.DealOrders.FirstOrDefault(p => p.OrderNo == orderNo);
                    if (d != null)
                    {
                        var m = Convertor.ConvertTo<DealOrderModel, DealOrder>(d);
                        m.Customer = Convertor.ConvertTo<CustomerModel, Customer>(d.Customer);
                        m.Items = Convertor.ConvertCollection<DealOrderDetailModel, DealOrderDetail, DealOrderDetailCollection>(d.DealOrderDetails);
                        foreach (var o in m.Items)
                        {
                            var di = d.DealOrderDetails.FirstOrDefault(p => p.ID == o.ID);
                            o.Product = Convertor.ConvertTo<ProductModel, Product>(di.Product);
                            o.MaterialName = di.ProductMaterial.MaterialName;
                            o.ProcessName = di.ProductProcess.ProcessName;
                        }
                        m.ProductOrders = Convertor.ConvertCollection<ProductOrderModel, ProductOrder, ProductOrderCollection>(d.ProductOrders);
                        m.ProductOrders.ForEach(p => {
                            var po = d.ProductOrders.FirstOrDefault(o => o.ID == p.ID);
                            p.Items = Convertor.ConvertCollection<ProductOrderDetailModel, ProductOrderDetail, ProductOrderDetailCollection>(po.ProductOrderDetails);
                        });
                        return m;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 撤消交易单据
        /// </summary>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        public static bool CancelOrder(string orderNo)
        {
            if (!string.IsNullOrEmpty(orderNo))
            {
                using (DBCentre db = new DBCentre())
                {
                    var order = db.DataContext.DealOrders.FirstOrDefault(p => p.OrderNo == orderNo);
                    if (order != null)
                    {
                        if (order.OrderStatus!=(int)OrderStatus.New)
                            throw new InvoicingException("这个单据不是新单据，不能撤消。");
                        order.OrderStatus = (int)OrderStatus.Cancel;
                        db.DataContext.SaveChanges();
                        return true;
                    }
                    else
                        throw new InvoicingException("无效的单据编号。");
                }
            }
            return false;
        }
    }
}
